<template>
  <div class="address-list">
    <h1>地址管理</h1>
    <div v-for="(addr, index) in addresses" :key="index" class="address-item">
      <div class="address-details">
        <div>姓名：{{ addr.name }}</div>
        <div>电话：{{ addr.phone }}</div>
        <div>地址：{{ addr.address }}</div>
      </div>
      <van-button type="primary" size="small" @click="selectAddress(addr)">选择此地址</van-button>
    </div>
    <router-link :to="{ name: 'addressAdd' }">
      <van-button type="primary" size="small">添加新地址</van-button>
    </router-link>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';

const router = useRouter();
const addresses = ref([]);

onMounted(() => {
  const savedAddresses = localStorage.getItem('addresses');
  if (savedAddresses) {
    addresses.value = JSON.parse(savedAddresses);
  }
});

const selectAddress = (addr) => {
  localStorage.setItem('selectedAddress', JSON.stringify(addr));
  showToast('地址已选择');
  router.back(); // 返回上一页
};
</script>

<style scoped>
.address-list {
  padding: 1rem;
  max-width: 600px;
  margin: 0 auto;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

h1 {
  text-align: center;
  color: #333;
  margin-bottom: 1rem;
}

.address-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1rem;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 1rem;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  padding: 1rem;
}

.address-details {
  flex: 1;
  margin-right: 1rem;
}

.address-details div {
  margin-bottom: 0.5rem;
  color: #555;
}

.van-button {
  background-color: #1989fa;
  border-color: #1989fa;
  color: #fff;
}

.van-button[disabled] {
  background-color: #ccc;
  border-color: #ccc;
}

.add-address-button {
  display: block;
  width: 100%;
  margin-top: 1rem;
  background-color: #1989fa;
  border-color: #1989fa;
  color: #fff;
}
</style>